package com.have.blog.xo.service.admin.impl;

import com.github.pagehelper.PageHelper;
import com.have.blog.base.constant.BlogConstant;
import com.have.blog.base.enums.BlogStatus;
import com.have.blog.commons.feign.PictureFeignClient;
import com.have.blog.model.api.CommonPage;
import com.have.blog.model.mapper.TLinkMapper;
import com.have.blog.model.models.TLink;
import com.have.blog.model.models.TLinkExample;
import com.have.blog.utils.MyStringUtils;
import com.have.blog.utils.ResultUtils;
import com.have.blog.xo.constant.MessageConstant;
import com.have.blog.xo.constant.SysConstant;
import com.have.blog.xo.service.admin.BlogRollService;
import com.have.blog.xo.uitls.WebUtil;
import com.have.blog.xo.vo.BlogRollVo;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
@SuppressWarnings("all")
public class BlogRollServiceImpl implements BlogRollService {

    @Autowired
    private TLinkMapper linkMapper;
    @Autowired
    private PictureFeignClient pictureFeignClient;
    @Autowired
    private WebUtil webUtil;

    @Override
    public String getPageList(BlogRollVo linkVO) {
        PageHelper.startPage(linkVO.getCurrentPage(), linkVO.getPageSize());
        TLinkExample example = new TLinkExample();
        TLinkExample.Criteria criteria = example.createCriteria();
        criteria.andStatusEqualTo(BlogStatus.ENABLE.getStatus());
        if (!StringUtils.isEmpty(linkVO.getKeyword()) && !StringUtils.isEmpty(linkVO.getKeyword().trim())) {
            criteria.andTitleLike("%" + linkVO.getKeyword().trim() + "%");
        }
        if (linkVO.getLinkStatus() != null) {
            criteria.andLinkStatusEqualTo(linkVO.getLinkStatus());
        }
        if(!StringUtils.isEmpty(linkVO.getOrderByAscColumn())) {
            String column = MyStringUtils.underLine(new StringBuffer(linkVO.getOrderByAscColumn())).toString();
            example.setOrderByClause(column + " asc");
        }else if(!StringUtils.isEmpty(linkVO.getOrderByDescColumn())) {
            String column = MyStringUtils.underLine(new StringBuffer(linkVO.getOrderByDescColumn())).toString();
            example.setOrderByClause(column + " desc");
        } else {
            example.setOrderByClause("sort desc");
        }
        List<TLink> linkList = linkMapper.selectByExample(example);

        StringBuilder sb = new StringBuilder();
        linkList.forEach(item -> {
            if (!StringUtils.isEmpty(item.getFileUid())) {
                sb.append(item.getFileUid() + SysConstant.FILE_SEGMENTATION);
            }
        });

        String pictureList = null;
        Map<String, String> pictureMap = new HashMap<>();
        if (!StringUtils.isEmpty(sb.toString())) {
            pictureList = pictureFeignClient.getPicture(sb.toString(), SysConstant.FILE_SEGMENTATION);
        }
        List<Map<String, Object>> pictures = webUtil.getPictureMap(pictureList);
        pictures.forEach(item -> {
            pictureMap.put(item.get(SysConstant.UID).toString(), item.get(SysConstant.URL).toString());
        });
        for (TLink item : linkList) {
            if (!StringUtils.isEmpty(item.getFileUid())) {
                List<String> tempPictureUidList = MyStringUtils.changeStringToStringList(item.getFileUid(), BlogConstant.SYMBOL_COMMA);
                List<String> picUrlTemp = new ArrayList<>();
                tempPictureUidList.forEach(uid -> {
                    picUrlTemp.add(pictureMap.get(uid));
                });
                item.setPhotoList(picUrlTemp);
            }
        }
        return ResultUtils.successWithData(CommonPage.restPage(linkList));
    }

    @Override
    public String addBlogRoll(BlogRollVo linkVO) {
        TLink link = new TLink();
        BeanUtils.copyProperties(linkVO, link);
        link.setUid(MyStringUtils.getUUID());
        link.setCreateTime(new Date());
        link.setUpdateTime(new Date());
        link.setStatus(BlogStatus.ENABLE.getStatus());
        link.setClickCount(0);
        int result = linkMapper.insert(link);
        if (result <= 0) {
            return ResultUtils.errorWithMessage(MessageConstant.INSERT_FAIL);
        }

        // 通过消息队列发送邮件到站长邮箱
//        if(StringUtils.isNotEmpty(link.getEmail()) && CheckUtils.checkEmail(link.getEmail())) {
//            log.info("发送友链申请通过的邮件通知");
//            String linkApplyText =  "<a href=\" " + link.getUrl() + "\">" + link.getTitle() + "</a> 站长，您申请的友链已经成功上架~";
//            rabbitMqUtil.sendSimpleEmail(link.getEmail(), linkApplyText);
//        }

        // 删除redis中的友情链接
        deleteRedisBlogLinkList();
        return ResultUtils.successWithMessage(MessageConstant.INSERT_SUCCESS);
    }


    @Override
    public String editBlogRoll(BlogRollVo linkVO) {
        TLink link = linkMapper.selectByPrimaryKey(linkVO.getUid());

        Integer linkStatus = link.getLinkStatus();
        link.setTitle(linkVO.getTitle());
        link.setSummary(linkVO.getSummary());
        link.setLinkStatus(linkVO.getLinkStatus());
        link.setUrl(linkVO.getUrl());
        link.setSort(linkVO.getSort());
        link.setEmail(linkVO.getEmail());
        link.setFileUid(linkVO.getFileUid());
        link.setUpdateTime(new Date());
        int result = linkMapper.updateByPrimaryKeySelective(link);
        if (result < 1) {
            return ResultUtils.errorWithMessage(MessageConstant.UPDATE_FAIL);
        }

        // 友链从申请状态到发布状态，需要发送邮件到站长邮箱
//        if(StringUtils.isNotEmpty(link.getEmail()) && CheckUtils.checkEmail(link.getEmail())) {
//            if(ELinkStatus.APPLY.equals(linkStatus) && ELinkStatus.PUBLISH.equals(linkVO.getLinkStatus())) {
//                log.info("发送友链申请通过的邮件通知");
//                String linkApplyText =  "<a href=\" " + link.getUrl() + "\">" + link.getTitle() + "</a> 站长，您申请的友链已经成功上架~";
//                rabbitMqUtil.sendSimpleEmail(link.getEmail(), linkApplyText);
//            }
//        }

        // 删除Redis中的BLOG_LINK
        deleteRedisBlogLinkList();

        return ResultUtils.successWithMessage(MessageConstant.UPDATE_SUCCESS);
    }


    @Override
    public String deleteBlogRoll(BlogRollVo linkVO) {
        TLink link = linkMapper.selectByPrimaryKey(linkVO.getUid());
        link.setStatus(BlogStatus.DISABLE.getStatus());
        link.setUpdateTime(new Date());
        int result = linkMapper.updateByPrimaryKeySelective(link);
        if (result <= 0) {
            return ResultUtils.errorWithMessage(MessageConstant.DELETE_FAIL);
        }

        // 删除Redis中的BLOG_LINK
        deleteRedisBlogLinkList();

        return ResultUtils.successWithMessage(MessageConstant.DELETE_SUCCESS);
    }

    @Override
    public String stictBlogRoll(BlogRollVo linkVO) {
        PageHelper.startPage(1, 1);
        TLink link = linkMapper.selectByPrimaryKey(linkVO.getUid());
        //查找出最大的那一个
        TLinkExample example = new TLinkExample();
        example.createCriteria()
                .andStatusEqualTo(BlogStatus.ENABLE.getStatus());
        example.setOrderByClause("sort desc");

        List<TLink> links = linkMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(links)) {
            return ResultUtils.successWithMessage(MessageConstant.OPERATION_SUCCESS);
        }
        TLink maxSort = links.get(0);
        if (maxSort.getUid().equals(link.getUid())) {
            return ResultUtils.successWithMessage(MessageConstant.OPERATION_SUCCESS);
        }
        Integer sortCount = maxSort.getSort() + 1;
        link.setSort(sortCount);
        link.setUpdateTime(new Date());
        int result = linkMapper.updateByPrimaryKeySelective(link);
        // 删除Redis中的BLOG_LINK
        if (result <= 0) {
            return ResultUtils.errorWithMessage(MessageConstant.OPERATION_FAIL);
        }
        deleteRedisBlogLinkList();
        return ResultUtils.successWithMessage(MessageConstant.OPERATION_SUCCESS);
    }

    private void deleteRedisBlogLinkList() {

    }
}
